package priv.dk.springboot.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import priv.dk.springboot.domain.entity.Category;
import priv.dk.springboot.domain.entity.Employee;
import priv.dk.springboot.service.CategoryService;
import priv.dk.springboot.util.RespBean;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @GetMapping
    @ResponseBody
    public List<Category> getAll() {
        return categoryService.getAll();
    }

    @PostMapping
    @ResponseBody
    public RespBean<String> addCategory(HttpSession session, @RequestBody(required = false) Category category) {
        // 参数校验
        if (category == null) return RespBean.error("非法参数");

        //配置参数
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());
        Employee employee = (Employee) session.getAttribute("employee");
        category.setCreateUser(employee.getId());
        category.setUpdateUser(employee.getId());

        categoryService.addCategory(category);
        return RespBean.ok();
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public RespBean<String> remove(@PathVariable Integer id) {
        if (id == null) return RespBean.error("非法参数");

        categoryService.remove(id);
        return RespBean.ok();
    }

    @PutMapping
    @ResponseBody
    public RespBean<String> modify(HttpSession session, @RequestBody(required = false) Category category) {
        // 校验参数
        if (category == null) return RespBean.error("非法参数");
        // 配置参数
        Employee employee = (Employee) session.getAttribute("employee");
        category.setUpdateUser(employee.getId());
        category.setUpdateTime(new Date());
        // 执行修改业务
        categoryService.modify(category);

        return RespBean.ok();
    }
}
